package com.j1ay.forum.service.impl;

import com.alibaba.fastjson.JSON;
import com.j1ay.forum.dao.mapper.PermissionMapper;
import com.j1ay.forum.model.dto.params.UpdateUserParams;
import com.j1ay.forum.model.pojo.JwtUser;
import com.j1ay.forum.model.pojo.po.Permission;
import com.j1ay.forum.model.pojo.po.User;
import com.j1ay.forum.model.pojo.vo.ErrorCode;
import com.j1ay.forum.service.UserService;
import com.j1ay.forum.utils.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Author J1ay
 * @Date 2021/12/20 13:15
 * @Description security 自定义方法：根据用户名在数据库查询该用户信息和对应权限
 */

@Component
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;
    @Autowired(required = false)
    private PermissionMapper permissionMapper;

    private JwtTokenUtil jwtTokenUtil;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询用户信息

        User user = userService.findUserById(username);

        // 账号不存在
        if (Objects.isNull(user)) {
            throw new UsernameNotFoundException(ErrorCode.ACCOUNT_USER_NOT_EXIST.getMsg());
        }

        // 更新用户登录时间
        user.setLastLogin(new Date());
        userService.lastLogin(user);

        // 查询用户权限
        List<Permission> permissionList = permissionMapper.findPermissionsByRoleId(user.getRoleId());
        List<SimpleGrantedAuthority> simpleGrantedAuthorities = new ArrayList<>();
        for (int i = 0; i < permissionList.size(); ++i) {
            simpleGrantedAuthorities.add(new SimpleGrantedAuthority(permissionList.get(i).getPath()));
        }

        return new JwtUser(user.getId(), username, user.getPassword(), simpleGrantedAuthorities);
    }

    public static void main(String[] args) {
        System.out.println(new BCryptPasswordEncoder().encode("123456"));
        System.out.println(new BCryptPasswordEncoder().encode("e10adc3949ba59abbe56e057f20f883e"));
    }
}
